
namespace LeetCode0119GetRow {

    // 直接公式计算
    function getRow(rowIndex: number): number[] {
        if (rowIndex < 0) return [];
        let ans: number[] = new Array();
        for (let i = 0; i <= rowIndex; i++) {
            const val: number = (i == 0 || i == rowIndex) ? 1 : (((i == 1 || i == rowIndex - 1)) ? rowIndex : ans[i - 1] * (rowIndex - (i - 1)) / i);
            ans.push(val);
        }
        return ans;
    };

    // 优化计算开销，只计算前半个数组
    function getRow1(rowIndex: number): number[] {
        if (rowIndex < 0) return [];
        let ans: number[] = new Array();
        // 中位pos
        const midPos: number = rowIndex >= 2 ? Math.ceil((rowIndex - 1) / 2) : 0;
        for (let i = 0; i <= rowIndex; i++) {
            // 先处理第0、1、rowIndex-1、rowIndex处的4个特值
            let val: number = (i == 0 || i == rowIndex) ? 1 : (((i == 1 || i == rowIndex - 1)) ? rowIndex : 0);
            // 处理中间值，前一般需要数学计算，后一半直接对称取值
            if (val == 0) {
                if (i <= midPos) {
                    // 前一个数字的下标
                    const last: number = i - 1;
                    val = ans[last] * (rowIndex - last) / i
                } else {
                    const pos: number = 2 * midPos - i + (rowIndex % 2);
                    val = ans[pos];
                }

            }
            ans.push(val);
        }
        return ans;
    }

    // test
    process.stdin.resume();
    process.stdout.write('求取杨辉三角第N行数组：n=');
    process.stdin.on('data', function (data: Buffer) {
        const N: number = parseInt(String(data));
        // process.stdin.pause();
        const ans: number[] = getRow1(N);
        console.log(JSON.stringify(ans));
    });

    // debug test
    // getRow1(8);
}